<?php
/**
 * @package YARBB
 * @copyright Авторские права (C) 2009 www.yar-it.com. Все права защищены.
 * @license Лицензия http://www.gnu.org/licenses/gpl-2.0.htm GNU/GPL, или help/license.php
 * YARBB! - свободное программное обеспечение распространяемое по условиям лицензии GNU/GPL
 * Для получения информации о используемых расширениях и замечаний об авторском праве, смотрите файл copyright.php.
 */
// no direct access
defined( '_VALID_MOS' ) or die();

require $yarbb_admin_path.'/include/core.php';

if ($yarbb_user['g_id'] > YARBB_MOD)
	mosRedirect(sefRelToAbs(YARBB_URL), _NOT_AUTH);
if (isset($_GET['id']) || isset($_GET['ids'])) {
	if (isset($_GET['ids'])) {
		$post_ids = $_GET['ids'];
		if (@preg_match('/[^0-9,]/', $post_ids))
			mosRedirect(sefRelToAbs(YARBB_URL), _Y_404);
		if (strpos($post_ids, ',') === false) {
			// there is only one post to move, so no special multi-moves
			$post_id = $post_ids;
			unset($post_ids);
		} else {
			// we presume all the posts we want to move are from the same
			// topic. So, for the information, we just take the first id
			$post_id = intval(substr($post_ids, 0, strpos($post_ids, ',')));
		}
	} else
		$post_id = intval($_GET['id']);

	//Поиск информации оригинального сообщ.
	$sql = ('SELECT p.message, t.id, t.subject, t.forum_id, f.forum_name
				FROM #__forum_posts as p 
				INNER JOIN #__forum_topics as t ON p.topic_id=t.id 
				INNER JOIN #__forum_forums as f ON t.forum_id=f.id 
				WHERE p.id='.$post_id) ;
	$info_post_result = $database->setQuery($sql)->loadRow();

	if (!$info_post_result)
		mosRedirect(sefRelToAbs(YARBB_URL), _Y_404);

	list($message, $old_topic_id, $subject, $old_fid, $forum_name) = $info_post_result;

	//Same forum or new one ?
	if (isset($_GET['new_fid'])) {
		$fid =$new_fid = intval($_GET['new_fid']);

		if ($new_fid != $old_fid)
			$new_forum = TRUE;
		else
			$fid = $old_fid;
	} else
		$fid = $old_fid;


	if (isset($_POST['form_sent']))
		$form_sent = intval($_POST['form_sent']);

	if ($form_sent > 1) {
		$topic_radio = $_POST['topic_to_move'];
		$topic_plain = yarbb_trim($_POST['topic_to_move_plain']);
		if(($topic_plain && $topic_radio) || ($topic_plain && !is_numeric($topic_plain)))
			mosRedirect(sefRelToAbs(YARBB_URL.'&amp;task=movepost&amp;id='.$post_id), _Y_MOVBADPOST);

		$new_topic_id = ($topic_plain) ? $topic_plain : $topic_radio;

		if ($new_topic_id == '' && $form_sent != 2)
			mosRedirect(sefRelToAbs(YARBB_URL.'&amp;task=movepost&amp;id='.$post_id), _Y_MOVBADPOST);
		//Тот же самый форум или другой?
		if($topic_plain) {
			$sql = ('SELECT forum_id FROM #__forum_topics
					WHERE id='.$new_topic_id);
			$fid_result = $database->setQuery($sql)->loadResult();

			if (!$fid_result)
				mosRedirect(sefRelToAbs(YARBB_URL), _Y_404);

			$fid = $new_fid = $fid_result;
			if ($new_fid != $old_fid)
				$new_forum = TRUE;
			else
				$fid = $old_fid;
		}
		// If we need to move all the posts
		if (isset($_POST['move_all_post'])) {
			$all_id=TRUE;
			// Get the posts ID
			$sql = ('SELECT id, message FROM #__forum_posts
						WHERE topic_id='.$old_topic_id.' 
						ORDER BY posted');
			$get_post_id = $database->setQuery($sql)->loadRow();
			if (!$get_post_id)
				mosRedirect(sefRelToAbs(YARBB_URL), _Y_404);
			else {
				//get the first post to check if it is $post_id
				list($first_post_id, $first_message) = $get_post_id;
				if ($first_post_id != $post_id) {
					$post_id = $first_post_id;
					$message = $first_message;
				}

				// get all the others post_id
				$all_post_id = $post_id;
				while ($row = $get_post_id)
					$all_post_id .= ','.$row[0];
			}
		}
		// If it's a creation of a new topic
		if ($form_sent == 2) {
			$new_subject = yarbb_trim($_POST['create_topic']);

			if ($new_subject == '')
				mosRedirect(sefRelToAbs(YARBB_URL.'&amp;task=movepost&amp;id='.$post_id), _OBJECT_MUST_HAVE_TITLE);


			// Если это создание новой темы
			$sql = ('INSERT INTO #__forum_topics (subject, forum_id)
						VALUES(\''.$database->getEscaped($new_subject).'\', '.$fid.')');
			$database->setQuery($sql);
			$database->Query($sql);
			$new_topic_id = $database->insertid();
		}
		else {
			// Determine if the post will be in first position in the reception topic ($new_topic_id)
			$database->setQuery('SELECT p.id, p.message, t.subject FROM #__forum_posts as p INNER JOIN #__forum_topics as t ON p.topic_id=t.id WHERE p.topic_id='.$new_topic_id.' ORDER BY p.posted LIMIT 1');
			$database->query();
			$reception_num_post = $database->getNumRows();
			if ($reception_num_post < 1)
				mosRedirect(sefRelToAbs(YARBB_URL), _Y_404);

			list($reception_topic_first_post_id, $reception_first_message, $reception_subject) = $database->loadRow();

			$is_reception_post_new = ($reception_topic_first_post_id > $post_id) ? true : false;
		}
		// Determine whether this post is the first post of the old topic or not AND if there is a second post or not
		//s
		$result = $database->setQuery('SELECT id, message FROM #__forum_posts WHERE topic_id='.$old_topic_id.' ORDER BY posted LIMIT 2');
		$database->query();
		$num_post = $database->getNumRows();
		if ($num_post < 1)
			mosRedirect(sefRelToAbs(YARBB_URL), _Y_404);
		$rows=$database->loadRowList();
		list($first_post_id,) = $rows[0];
		list($second_post_id, $second_message) = $rows[1];

		if ($num_post == 1)
			$is_topic_post=TRUE;

		if ($num_post > 1  && $first_post_id == $post_id && !$all_id )
			$is_second_post=TRUE;
		//Move post(s) in the new topic
		if ($all_id) {
			$database->setQuery('UPDATE #__forum_posts SET topic_id='.$new_topic_id.' WHERE id IN('.$all_post_id.')');
			$database->query();
		}
		else {
			if (isset($post_ids)) {
				$post_ids = explode(',', $post_ids);
				foreach ($post_ids as $post_id_this) {
					$database->setQuery('UPDATE #__forum_posts SET topic_id='.$new_topic_id.' WHERE id='.$post_id_this);
					$database->query();
				}
			}
			else {
				$database->setQuery('UPDATE #__forum_posts SET topic_id='.$new_topic_id.' WHERE id='.$post_id);
				$database->query();
			}
		}
		//Update tables search
		if($all_id || $is_topic_post || $is_second_post) //if the moved post was in first position in the original topic
		{
			require_once $yarbb_admin_path.'/include/search_idx.php';
			strip_search_index($post_id); // remove the entries in the tables
			if ($new_subject)
				update_search_index('movepost', $post_id, $message,$new_subject); // update message and subject
			else
				update_search_index('movepost', $post_id, $message); // update only message

			if ($is_second_post) //if the next post is now in first position in the old topic
			{
				strip_search_index($second_post_id);
				update_search_index('movepost', $second_post_id, $second_message,$subject);
			}
		}

		if ($is_reception_post_new) // if the moved post is in first position on the reception topic
		{
			require_once $yarbb_admin_path.'/include/search_idx.php';

			// update the post which was first one on the reception topic (and second now)
			strip_search_index($reception_topic_first_post_id);
			update_search_index('movepost', $reception_topic_first_post_id, $reception_first_message);

			// update the post which is now the first one on the reception topic
			strip_search_index($post_id);
			update_search_index('movepost', $post_id, $message, $reception_subject);
		}
		//Update topics and forum if required
		update_topic($new_topic_id);

		if($is_topic_post || $all_id) {
			delete_topic($old_topic_id);
			update_forum($old_fid); // Update the forum FROM which the topic was moved

			if($new_forum)
				update_forum($new_fid);	// Update the forum FROM which the topic was moved
		}
		else {
			update_topic($old_topic_id);

			if($new_forum) {
				update_forum($old_fid);	// Update the forum FROM which the topic was moved
				update_forum($new_fid);	// Update the forum TO which the topic was moved
			}
		}
		mosRedirect( sefRelToAbs(YARBB_URL.'&amp;task=viewtopic&amp;pid='.$post_id).'#p'.$post_id, _Y_MOVSUCCES);
	}
	else // Display the form
	{
		// If multiple most must be move, you can't move all the posts at the same time
		if (!isset($post_ids)) {
			// Count the number of posts in the topic
			//s
			$sql = ('SELECT count(id) FROM #__forum_posts WHERE topic_id='.$old_topic_id);
			$num_post = $database->setQuery($sql)->loadResult();

			//Count the topics to diplayed
			$result = $database->setQuery('SELECT count(id) FROM #__forum_topics WHERE forum_id ='.$fid.' AND moved_to IS NULL');
			$num_topics = $database->loadResult();

			//Not add the original topic
			if ($fid == $old_fid)
				$num_topics = $num_topics-1;
		}

		//Sort query (based on $_GET['new_fid'], $_GET['sort'] and $_GET['desc'])
		$var_query_img = $var_query = '';
		if (isset($_GET['new_fid']))
			$var_query_img .= $var_query .='&new_fid='.$fid;

		if (isset($_GET['sort'])) {
			$sort_list= $_GET['sort'];
			$var_query .='&sort='.$sort_list;

			if (isset($_GET['desc'])) {
				$sort_list .=' DESC';
				$var_query .='&desc=1';
			}
		}
		else
			$sort_list= 'last_post DESC';

		// Determine the topic offset (based on $_GET['p'])
		$num_pages = ceil($num_topics / $yarbb_user['disp_topics']);
		$p = (!isset($_GET['p']) || $_GET['p'] <= 1 || $_GET['p'] > $num_pages) ? 1 : $_GET['p'];
		$start_from = $yarbb_user['disp_topics'] * ($p - 1);

		// Generate paging links
		$paging_links = _PN_PAGE.': '.paginate($num_pages, $p, ''.YARBB_URL.'&amp;task=movepost&amp;id='.$post_id.$var_query);
		//The topic query
		$database->setQuery('SELECT id, subject, poster, last_post, num_replies FROM #__forum_topics WHERE moved_to IS NULL AND forum_id='.$fid.' AND id <> '.$old_topic_id.' ORDER BY '.$sort_list.' LIMIT '.$start_from.','.$yarbb_user['disp_topics']);
		$database->query();
		$rows1=$database->loadAssocList();
		$num1=$database->getNumRows();

		echo $mainframe->setPageTitle( _Y_MOVEPOST.' - '.yarbb_htmlspecialchars($yarbb_config['o_board_title']));
		?>

<table width="97%" border="0" cellspacing="0" cellpadding="0">
	<tr>
		<td><div class="blockform">
				<h2><span><?php echo _Y_MOVEPOST; ?></span></h2>
				<div class="box">
					<form id="qjump" method="get" action="<?php echo YARBB_URL ?>&amp;task=movepost&amp;<?php echo (isset($post_ids)?'ids='.$post_ids:'&amp;id='.$post_id) ?>">
						<p><strong><a href="<?php echo sefRelToAbs(YARBB_URL."&amp;task=viewtopic&amp;pid=".$post_id)."#p".$post_id; ?>"><?php echo _Y_MENU_BACK; ?></a></strong></p>
						<br />
						<fieldset>
							<legend><?php echo _Y_MOVEINTRO; ?></legend>
							<hr/>
							<div class="infldset">
								<p><?php echo _Y_MOVEINFO; ?></p>
								<br />
								<p><?php echo _Y_MOVORIGTOP; ?>: <strong><?php echo yarbb_htmlspecialchars($subject) ?></strong></p>
								<p><?php echo _Y_MOVORIGFOR; ?>: <strong><?php echo yarbb_htmlspecialchars($forum_name) ?></strong></p>
								<p><?php echo _Y_FORUMED; ?>:</p>
								<div>
									<select name="id" onchange="window.location=('<?php echo YARBB_URL ?>&amp;task=movepost<?php echo (isset($post_ids)?'&amp;ids='.$post_ids:'&amp;id='.$post_id) ?>&amp;new_fid='+this.options[this.selectedIndex].value)">
		<?php
		$sql = 'SELECT c.id AS cid, c.cat_name, f.id AS fid, f.forum_name FROM #__forum_categories AS c INNER JOIN #__forum_forums AS f ON c.id=f.cat_id LEFT JOIN #__forum_forum_perms AS fp ON (fp.forum_id=f.id AND fp.group_id='.$yarbb_user['g_id'].') WHERE (fp.read_forum IS NULL OR fp.read_forum=1) AND f.redirect_url IS NULL ORDER BY c.disp_position, c.id, f.disp_position';
		$cur_category = 0;
		$rows=$database->setQuery($sql)->loadAssocList();
		foreach($rows as $cur_forum ) {
			if ($cur_forum['cid'] != $cur_category)	// A new category since last iteration?
			{
				if ($cur_category)
					echo "\t\t\t\t\t\t".'</optgroup>'."\n";

				echo "\t\t\t\t\t\t".'<optgroup label="'.yarbb_htmlspecialchars($cur_forum['cat_name']).'">'."\n";
				$cur_category = $cur_forum['cid'];
			}

			echo "\t\t\t\t\t\t\t<option value=".$cur_forum['fid'];
			if ($cur_forum['fid'] == $fid) echo " selected='selected'";
			echo " >".yarbb_htmlspecialchars($cur_forum['forum_name'])."</option>\n";
		}
		?>
										</optgroup>
									</select>
								</div>
							</div>
						</fieldset>
						<input type="hidden" name="form_sent" value="1" />
					</form>
					<form id="movepost_create" method="post" action="<?php echo YARBB_URL ?>&amp;task=movepost&amp;<?php echo (isset($post_ids)?'ids='.$post_ids:'&amp;id='.$post_id) ?>&amp;new_fid=<?php echo $fid ?>">
						<fieldset>
							<legend><?php echo _Y_YARNEWTOP; ?></legend>
							<hr/>
							<div class="infldset">
								<p><?php echo _Y_MOVEENTSUBG; ?></p>
								<br />
								<input name="create_topic" size="70" maxlength="70" tabindex="1" type="text" />
								<input name="save" value="<?php echo _SUBMIT_BUTTON; ?>" type="submit" />
												<?php if (!isset($post_ids)) {
													?>
								<br />
								<br />
								<p><?php echo _Y_MOVEALLPOST; ?> (<strong><?php echo _Y_RSSKOLVOPOST; ?>:&nbsp;<?php echo $num_post ?></strong>)</p>
								<div class="rbox">
									<label>
										<input name="move_all_post" value="1" type="checkbox" />
			<?php echo _Y_MOVEORGDEL; ?> <br />
									</label>
								</div>
			<?php } ?>
							</div>
						</fieldset>
						<input type="hidden" name="form_sent" value="2" />
					</form>
					<form id="movepost_move" method="post" action="<?php echo YARBB_URL ?>&amp;task=movepost&amp;<?php echo (isset($post_ids)?'ids='.$post_ids:'&amp;id='.$post_id) ?>">
		<?php if ($new_fid) echo '&amp;new_fid='.$new_fid;?>
						<fieldset>
							<legend><?php echo _Y_MOVENTTOPS; ?></legend>
							<hr />
							<div class="infldset">
								<p><?php echo _Y_MOVEALLPOST; ?> (<strong><?php echo _Y_RSSKOLVOPOST; ?>:&nbsp;<?php echo $num_post ?></strong>)</p>
		<?php if (!isset($post_ids)) {
											?>
								<div class="rbox">
									<label>
										<input name="move_all_post" value="1" type="checkbox" />
			<?php echo _Y_MOVEORGDEL; ?> <br />
									</label>
								</div>
								<br />
								<hr />
													<?php } ?>
								<p><strong><?php echo _Y_MOVENTTOPS2; ?></strong></p>
								<br />
								<input name="topic_to_move_plain" size="10" maxlength="10" tabindex="1" type="text" />
								<input name="save" value="<?php echo _SUBMIT_BUTTON; ?>" type="submit" />
								<br />
								<br />
								<hr />
								<p><strong><?php echo _Y_MOVENTTOPS3; ?></strong></p>
								<br />
								<p style="TEXT-ALIGN:center;">
									<input name="save" value="<?php echo _SUBMIT_BUTTON; ?>" type="submit" />
								</p>
								<p class="pagelink conl"><?php echo $paging_links ?></p>
								<p>&nbsp;</p>
								<table width="100%" cellspacing="0" class="aligntop">
									<tr>
										<th class="tc2" scope="col"> <input name="topic_to_move" value="" type="radio" />                  </th>
										<th scope="col"> <strong><?php echo _Y_TOPICS; ?></strong>
											<a href="<?php echo sefRelToAbs(YARBB_URL.'&amp;task=movepost&amp;id='.$post_id.$var_query_img.'&sort=subject'); ?>"><img alt="up" SRC="components/com_forum/images/movepost/arrow_up.png"></a> <a href="<?php echo sefRelToAbs(YARBB_URL.'&amp;task=movepost&amp;id='.$post_id.$var_query_img.'&sort=subject&desc=1'); ?>"><img alt="down" SRC="components/com_forum/images/movepost/arrow_down.png"></a> </th>
										<th scope="col"> <strong><?php echo _Y_YARBY; ?></strong>
											<a href="<?php echo sefRelToAbs(YARBB_URL.'&amp;task=movepost&amp;id='.$post_id.$var_query_img.'&sort=subject'); ?>"><img alt="up" src="components/com_forum/images/movepost/arrow_up.png" /></a><a href="<?php echo sefRelToAbs(YARBB_URL.'&amp;task=movepost&amp;id='.$post_id.$var_query_img.'&sort=subject'); ?>"></a><a href="<?php echo sefRelToAbs(YARBB_URL.'&amp;task=movepost&amp;id='.$post_id.$var_query_img.'&sort=subject&desc=1'); ?>"><img alt="down" SRC="components/com_forum/images/movepost/arrow_down.png"></a> </th>
										<th scope="col"> <strong><?php echo _Y_LASTPOST; ?></strong>
											<a href="<?php echo sefRelToAbs(YARBB_URL.'&amp;task=movepost&amp;id='.$post_id.$var_query_img.'&sort=subject'); ?>"><img alt="up" SRC="components/com_forum/images/movepost/arrow_up.png"></a> <a href="<?php echo sefRelToAbs(YARBB_URL.'&amp;task=movepost&amp;id='.$post_id.$var_query_img.'&sort=subject&desc=1'); ?>"><img alt="down" SRC="components/com_forum/images/movepost/arrow_down.png"></a> </th>
										<th class="tc2" scope="col"> <strong><?php echo _Y_REPLYSY; ?></strong>
											<a href="<?php echo sefRelToAbs(YARBB_URL.'&amp;task=movepost&amp;id='.$post_id.$var_query_img.'&sort=subject'); ?>"><img alt="up" SRC="components/com_forum/images/movepost/arrow_up.png"></a> <a href="<?php echo sefRelToAbs(YARBB_URL.'&amp;task=movepost&amp;id='.$post_id.$var_query_img.'&sort=subject&desc=1'); ?>"><img alt="down" SRC="components/com_forum/images/movepost/arrow_down.png"></a> </th>
									</tr>
		<?php
		// If there are topics in this forum.
		if (!$num1) {
			foreach ($rows1 as $cur_topic ) {
				?>
									<tr>
										<td class="tc2"><input name="topic_to_move" value="<?php echo $cur_topic['id'] ?>" type="radio" /></td>
										<td><?php echo yarbb_htmlspecialchars($cur_topic['subject']) ?></td>
										<td><?php echo yarbb_htmlspecialchars($cur_topic['poster']) ?></td>
										<td><?php echo format_time($cur_topic['last_post']) ?></td>
										<td class="tc2"><?php echo $cur_topic['num_replies'] ?></td>
									</tr>
				<?php
			}
		}
		?>
									<tr>
										<th class="tc2" scope="col"> <input name="topic_to_move" value="" checked="checked" type="radio" />                  </th>
										<th scope="col"><strong><?php echo _Y_TOPICS; ?></strong>  <a href="<?php echo sefRelToAbs(YARBB_URL.'&amp;task=movepost&amp;id='.$post_id.$var_query_img.'&sort=subject'); ?>"><img alt="up" SRC="components/com_forum/images/movepost/arrow_up.png"></a> <a href="<?php echo sefRelToAbs(YARBB_URL.'&amp;task=movepost&amp;id='.$post_id.$var_query_img.'&sort=subject&desc=1'); ?>"><img alt="down" SRC="components/com_forum/images/movepost/arrow_down.png"></a>
										</th>
										<th scope="col">  <strong><?php echo _Y_YARBY; ?></strong><a href="<?php echo sefRelToAbs(YARBB_URL.'&amp;task=movepost&amp;id='.$post_id.$var_query_img.'&sort=subject'); ?>"><img alt="up" SRC="components/com_forum/images/movepost/arrow_up.png"></a> <a href="<?php echo sefRelToAbs(YARBB_URL.'&amp;task=movepost&amp;id='.$post_id.$var_query_img.'&sort=subject&desc=1'); ?>"><img alt="down" SRC="components/com_forum/images/movepost/arrow_down.png"></a>
										</th>
										<th scope="col"> <strong><?php echo _Y_LASTPOST; ?></strong><a href="<?php echo sefRelToAbs(YARBB_URL.'&amp;task=movepost&amp;id='.$post_id.$var_query_img.'&sort=subject'); ?>"><img alt="up" SRC="components/com_forum/images/movepost/arrow_up.png"></a> <a href="<?php echo sefRelToAbs(YARBB_URL.'&amp;task=movepost&amp;id='.$post_id.$var_query_img.'&sort=subject&desc=1'); ?>"><img alt="down" SRC="components/com_forum/images/movepost/arrow_down.png"></a>
										</th>
										<th class="tc2" scope="col">  <strong><?php echo _Y_REPLYSY; ?></strong><a href="<?php echo sefRelToAbs(YARBB_URL.'&amp;task=movepost&amp;id='.$post_id.$var_query_img.'&sort=subject'); ?>"><img alt="up" SRC="components/com_forum/images/movepost/arrow_up.png"></a> <a href="<?php echo sefRelToAbs(YARBB_URL.'&amp;task=movepost&amp;id='.$post_id.$var_query_img.'&sort=subject&desc=1'); ?>"><img alt="down" SRC="components/com_forum/images/movepost/arrow_down.png"></a>
										</th>
									</tr>
								</table>
								<p class="pagelink conl"><?php echo $paging_links ?></p>
								<p>&nbsp;</p>
								<p style= "TEXT-ALIGN: center;">
									<input name="save2" value="<?php echo _SUBMIT_BUTTON; ?>" type="submit" />
								</p>
							</div>
						</fieldset>
						<input type="hidden" name="form_sent" value="3" />
						<br />
						<p><strong><?php echo "<a href=\"".sefRelToAbs(YARBB_URL."&amp;task=viewtopic&amp;pid=".$post_id)."#p".$post_id."\" />" ?><?php echo _MENU_BACK; ?></a></strong></p>
					</form>
				</div>
			</div>
			 </td>
	</tr>
</table>
		<?php
	}
}
else
	mosRedirect(sefRelToAbs(YARBB_URL), _Y_404);
?>
